<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商品管理
 */
class Goods extends SHOPS_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->model('goods_mdl');
        $this->load->model('sort_mdl');
    }
    
    //商品列表
    public function index(){
        //分页
        $this->load->library('pagination');

        /** 查询当前查询分类的子类 */
        $sort = $this->input->get('search-sort',TRUE);
        if(!empty($sort)){
            $sort_arr = $this->sort_mdl->getf(intval($sort));
            $sort_arr[] = ['id'=>$sort];
        }
        
        $this->db->start_cache();
        /** 组装查询条件 */
        $url = '';

        $key = $this->input->get('keywords',TRUE);
        if(!empty($key)){
            $this->db->or_like('name',$key);
            $this->db->or_like('brand',$key);
            $url .= 'keywords='.$key.'&';
        }

        if(!empty($sort_arr)){
            $sort_id = [];
            foreach($sort_arr as $k => $v){
                $sort_id[] = $v['id'];
            }
            $this->db->where_in('sort_id',$sort_id);
            $url .= 'search-sort='.$sort.'&';
        }

        $store = $this->input->get('store',TRUE);
        $store = intval($store);
        if(!empty($store)){
            $this->db->where('store_id',$store);
            $url .= 'store='.$store.'&';
        }

        //排序方式链接组装
        $data['order'] = 'asc'; //前段排序方式
        $data['order_url'] = $url;
        $order = $this->input->get('sort',TRUE);
        if(!empty($order)){
            $order_arr = explode('_', $order);
            $if_order = false;
            if($order_arr[2] == 'asc' || $order_arr[2] == 'desc'){
                $if_order = true;
            }
            if($order_arr[0] = 'sort' && $if_order){
                switch ($order_arr[1]) {
                    case 'id':
                        $this->db->order_by('id',$order_arr[2]);
                    break;
                    case 'num':
                        $this->db->order_by('num',$order_arr[2]);
                    break;
                    case 'sales':
                        $this->db->order_by('sales',$order_arr[2]);
                    break;
                    case 'price':
                        $this->db->order_by('price',$order_arr[2]);
                    break;
                    case 'sprice':
                        $this->db->order_by('sprice',$order_arr[2]);
                    break;
                    case 'time':
                        $this->db->order_by('shelves',$order_arr[2]);
                    break;

                    default:
                        $this->db->order_by('id','desc');
                }
                $url .= 'sort='.$order.'&';
                $data['order'] = $order_arr[2]=='desc' ? 'asc' : 'desc';
            }
        }else{
            $this->db->order_by('id','desc');
        }

        $this->db->where('status !=',0);
        $this->db->where('store_id',self::$store['id']);
        $this->db->stop_cache();

        //组装链接
        $path = site_url('shops/goods/index');
        if(!empty($url)){
            $path .= '?'.mb_substr($url,0,-1);
        }
        $config['base_url'] = $path;
        $config['total_rows'] = $this->goods_mdl->get_count();
        $config['per_page'] = 10;
        $config['page_query_string'] = TRUE;
        $config['first_link'] = '首页';
        $config['last_link'] = '尾页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['anchor_class'] = 'current';
        
        $this->pagination->initialize($config);
        
        $data['page'] = $this->pagination->create_links();
        
        //数据查询
        $per_page = $this->input->get('per_page',TRUE);
        $this->db->select('id,sort_id,name,num,sales,price,brand,shelves,origin,sprice');
        $this->db->limit($config['per_page'],intval($per_page));
        
        $list = $this->goods_mdl->select();
        //echo $this->db->last_query();
        $this->db->flush_cache();
        $data['list'] = $this->goods_mdl->restr($list);

        $sort_all = $this->goods_mdl->sortAll;
        
        //组装分类菜单
        $sort = empty($sort) ? 0 : intval($sort);
        $sort_list = $this->sort_mdl->get_fsort($sort,$sort_all);
        if(empty($sort)){
            $sort_list[0]['pid'] = '0';
            $sort_list[0]['id'] = '0';
            foreach($sort_all as $k => $v){
                if($v['pid'] == 0){
                    $sort_list[0]['content'][] = $v;
                }
            }
        }
        
        $data['sort_list'] = array_reverse($sort_list);

        $this->_view('goods_index',$data);
    }

    /**
     * 查询url 参数重组
     */
    public function czurl(){
        $post = $this->input->post(NULL,TRUE);

        if($post == NULL){
            show_404();
            exit;
        }

        $url = '';

        if(!empty($post['search-sort'])){
            $url .= 'search-sort='.$post['search-sort'].'&';
        }
        if(!empty($post['keywords'])){
            $url .= 'keywords='.$post['keywords'].'&';
        }

        $path = site_url('shops/goods/index');
        if(!empty($url)){
            $path .= '?'.mb_substr($url,0,-1);
        }

        redirect($path);

    }
    
    //操作商品
    public function create(){
        //是否有临时数据
        $this->db->where('status',0);
        $this->db->where('user_id',self::$suser['id']);
        $res = $this->goods_mdl->get_one();
        
        if(empty($res)){
            //添加数据
            $data = [
                'user_id' => self::$suser['id'],
                'status' => 0,
                'store_id' => self::$store['id']
            ];
            $this->goods_mdl->create($data);
            
            $data = [
                'id' => $this->db->insert_id(),
            ];
            $this->load->model('details_mdl');
            $this->details_mdl->create($data);
            
            $this->db->where('id',$data['id']);
            $res = $this->goods_mdl->get_one();
        }
        
        //查询所有顶级分类
        $this->db->where('pid',0);
        $sort_list = $this->sort_mdl->select();
        
        $this->_view('goods_create',[
            'sort_list' => $sort_list,
            'res' => $res
        ]);
    }

    //商品修改页面
    public function update(){
        $gid = $this->input->get('gid',TRUE);
        
        if(empty($gid)){
            show_error('参数错误！');
            exit;
        }
        
        $this->db->where('id',intval($gid));
        $res = $this->goods_mdl->get_one();
        
        if(empty($res)){
            show_error('参数错误！');
        }

        //查找分类
        $this->load->model('sort_mdl');
        $sort_list = $this->sort_mdl->get_fsort($res['sort_id']);
        
        $this->_view('goods_update',[
            'res' => $res,
            'sort_list' => array_reverse($sort_list)
        ]);
    }
    
    //商品验证/修改
    public function edit_goods(){
        if(!$this->input->is_ajax_request()){
            show_404();
            exit;
        }
        
        $post = $this->input->post(NULL,TRUE);

        if($post['store_id'] != self::$store['id']){
            die('参数错误!');
        }
        
        if(empty($post['id'])){
            die('参数错误！');
        }
        
        //商品信息验证
        if(empty($post['sort_id'])){
            die("请选择商品分类！");
        }
        if(empty($post['name'])){
            die('商品名称不能为空');
        }
        if(!is_numeric($post['num']) || $post['num'] < 0){
            die('商品数量请填写大于等于0的整数！');
        }
        
        if(empty($post['price']) || !is_numeric($post['price']) || $post['price'] < 0){
            die('请填写正确的商品价格');
        }
        
        if(empty($post['brand'])){
            die('品牌名称不能为空');
        }
        
        if(empty($post['shelves_time'])){
            die('商品上架时间不能为空！');
        }else{
            $post['shelves'] = strtotime($post['shelves_time']);
            unset($post['shelves_time']);
        }
        
        if(empty($post['origin'])){
            die('商品产地不能为空');
        }
        
        $post['create_time'] = $_SERVER['REQUEST_TIME'];
        //$post['user_id'] = self::$suser['id'];
        
        if($post['status'] == 0){
            $post['status'] = 3;
        }
        
        $this->db->where('id',$post['id']);
        
        
        $r = $this->goods_mdl->update($post);
        //echo $this->db->last_query();exit;
        
        echo $r === false ? '商品添加失败！' : 1;
    }

    /**
     * 商品删除
     */
    public function delete(){
        $gid = $this->input->post('gid');

        if(!$this->input->is_ajax_request()){
            show_404();
            exit;
        }

        /** 删除数据，并且删除相关选项 */
        $res = $this->goods_mdl->delete($gid);
        echo $res === true ? 1 : '删除失败！' ;

    }
}
